/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package com.emex.app.stuff.admin;

import com.emex.app.stuff.security.SecurityManager;
import com.emex.app.shared.data.Cost;
import com.emex.app.shared.data.CostType;
import com.emex.app.stuff.gui.CostDialog;
import com.emex.app.stuff.gui.model.CostTableModel;
import com.emex.app.stuff.gui.model.CostTypeComboBoxModel;
import com.emex.app.stuff.provider.CostDataProvider;
import com.emex.app.stuff.utils.DateUtils;
import com.emex.app.stuff.utils.ReportGenerator;
import com.emex.app.stuff.utils.UIUtils;
import java.util.List;
import net.sf.jasperreports.engine.JasperPrint;
import org.netbeans.api.settings.ConvertAsProperties;
import org.openide.awt.ActionID;
import org.openide.awt.ActionReference;
import org.openide.windows.TopComponent;
import org.openide.util.NbBundle.Messages;
import org.openide.windows.WindowManager;

/**
 * Top component which displays something.
 */
@ConvertAsProperties(
        dtd = "-//com.emex.app.stuff.admin//Cost//EN",
        autostore = false
)
@TopComponent.Description(
        preferredID = "CostTopComponent",
        //iconBase="SET/PATH/TO/ICON/HERE", 
        persistenceType = TopComponent.PERSISTENCE_NEVER
)
@TopComponent.Registration(mode = "editor", openAtStartup = false)
@ActionID(category = "Window", id = "com.emex.app.stuff.admin.CostTopComponent")
@ActionReference(path = "Menu/Отчетность" /*, position = 333 */)
@TopComponent.OpenActionRegistration(
        displayName = "#CTL_CostAction",
        preferredID = "CostTopComponent"
)
@Messages({
    "CTL_CostAction=Отчеты по расходам",
    "CTL_CostTopComponent=Отчеты по расходам",
    "HINT_CostTopComponent=Отчеты по расходам"
})
public final class CostTopComponent extends TopComponent {

    private CostTableModel costTableModel;

    public CostTopComponent() {
        initComponents();
        setName(Bundle.CTL_CostTopComponent());
        setToolTipText(Bundle.HINT_CostTopComponent());
        customInit();
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        costPopuMenu = new javax.swing.JPopupMenu();
        deleteItem = new javax.swing.JMenuItem();
        jScrollPane1 = new javax.swing.JScrollPane();
        costsTable = new org.jdesktop.swingx.JXTable();
        jPanel1 = new javax.swing.JPanel();
        jLabel2 = new javax.swing.JLabel();
        startDatePicker = new org.jdesktop.swingx.JXDatePicker();
        endDatePicker = new org.jdesktop.swingx.JXDatePicker();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();
        costTypeComboBox = new javax.swing.JComboBox();
        applyFilterButton = new javax.swing.JButton();
        resetFilterButton = new javax.swing.JButton();
        refreshCostTypesButton = new javax.swing.JButton();
        printButton = new javax.swing.JButton();
        summaLabel = new javax.swing.JLabel();

        org.openide.awt.Mnemonics.setLocalizedText(deleteItem, org.openide.util.NbBundle.getMessage(CostTopComponent.class, "CostTopComponent.deleteItem.text")); // NOI18N
        deleteItem.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                deleteItemActionPerformed(evt);
            }
        });
        costPopuMenu.add(deleteItem);

        costsTable.setComponentPopupMenu(costPopuMenu);
        costsTable.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                costsTableMouseClicked(evt);
            }
        });
        jScrollPane1.setViewportView(costsTable);

        jPanel1.setBorder(javax.swing.BorderFactory.createTitledBorder(org.openide.util.NbBundle.getMessage(CostTopComponent.class, "CostTopComponent.jPanel1.border.title"))); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel2, org.openide.util.NbBundle.getMessage(CostTopComponent.class, "CostTopComponent.jLabel2.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel3, org.openide.util.NbBundle.getMessage(CostTopComponent.class, "CostTopComponent.jLabel3.text")); // NOI18N

        org.openide.awt.Mnemonics.setLocalizedText(jLabel4, org.openide.util.NbBundle.getMessage(CostTopComponent.class, "CostTopComponent.jLabel4.text")); // NOI18N

        costTypeComboBox.setModel(new javax.swing.DefaultComboBoxModel(new String[] { "Загрузка..." }));

        org.openide.awt.Mnemonics.setLocalizedText(applyFilterButton, org.openide.util.NbBundle.getMessage(CostTopComponent.class, "CostTopComponent.applyFilterButton.text")); // NOI18N
        applyFilterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                applyFilterButtonActionPerformed(evt);
            }
        });

        org.openide.awt.Mnemonics.setLocalizedText(resetFilterButton, org.openide.util.NbBundle.getMessage(CostTopComponent.class, "CostTopComponent.resetFilterButton.text")); // NOI18N
        resetFilterButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                resetFilterButtonActionPerformed(evt);
            }
        });

        refreshCostTypesButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/refresh.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(refreshCostTypesButton, org.openide.util.NbBundle.getMessage(CostTopComponent.class, "CostTopComponent.refreshCostTypesButton.text")); // NOI18N
        refreshCostTypesButton.setToolTipText(org.openide.util.NbBundle.getMessage(CostTopComponent.class, "CostTopComponent.refreshCostTypesButton.toolTipText")); // NOI18N
        refreshCostTypesButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                refreshCostTypesButtonActionPerformed(evt);
            }
        });

        printButton.setIcon(new javax.swing.ImageIcon(getClass().getResource("/icons/print.png"))); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(printButton, org.openide.util.NbBundle.getMessage(CostTopComponent.class, "CostTopComponent.printButton.text")); // NOI18N
        printButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                printButtonActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jLabel2)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(startDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel3)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(endDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, 141, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jLabel4)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(costTypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, 151, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(applyFilterButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(resetFilterButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(refreshCostTypesButton)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(printButton)
                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                        .addComponent(jLabel2)
                        .addComponent(startDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(endDatePicker, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(jLabel3)
                        .addComponent(jLabel4)
                        .addComponent(costTypeComboBox, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(applyFilterButton)
                        .addComponent(resetFilterButton)
                        .addComponent(refreshCostTypesButton))
                    .addComponent(printButton))
                .addContainerGap())
        );

        summaLabel.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        org.openide.awt.Mnemonics.setLocalizedText(summaLabel, org.openide.util.NbBundle.getMessage(CostTopComponent.class, "CostTopComponent.summaLabel.text")); // NOI18N

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(this);
        this.setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jScrollPane1)
                    .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(summaLabel)
                        .addGap(0, 0, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(summaLabel)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(jScrollPane1, javax.swing.GroupLayout.DEFAULT_SIZE, 85, Short.MAX_VALUE)
                .addContainerGap())
        );
    }// </editor-fold>//GEN-END:initComponents

    private void resetFilterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_resetFilterButtonActionPerformed
        startDatePicker.setDate(null);
        endDatePicker.setDate(null);
        costTypeComboBox.setSelectedItem(null);
        costTypeComboBox.repaint();
    }//GEN-LAST:event_resetFilterButtonActionPerformed

    private void applyFilterButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_applyFilterButtonActionPerformed
        if (startDatePicker.getDate() == null) {
            UIUtils.showErrorMessage("Выберите дату начала");
            return;
        }
        if (endDatePicker.getDate() == null) {
            UIUtils.showErrorMessage("Выберите дату окончания");
            return;
        }
        CostType ct = (CostType) costTypeComboBox.getSelectedItem();
        Integer id = null;
        if (ct != null) {
            id = ct.getId();
        }
        List<Cost> costs = CostDataProvider.getInstance().getAllCostsByDateAndCostType(startDatePicker.getDate(), endDatePicker.getDate(), id);
        costTableModel = new CostTableModel(costs);
        costsTable.setModel(costTableModel);
        summaLabel.setText("Сумма: " + round(costTableModel.getSum(), 2));
    }//GEN-LAST:event_applyFilterButtonActionPerformed

    private void refreshCostTypesButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_refreshCostTypesButtonActionPerformed
        costTypeComboBox.setModel(new CostTypeComboBoxModel());
    }//GEN-LAST:event_refreshCostTypesButtonActionPerformed

    private void printButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_printButtonActionPerformed
        if (costsTable.getRowCount() > 0) {
            try {
                StringBuilder str = new StringBuilder();
                str.append(summaLabel.getText()).append("\\n");
                JasperPrint print = ReportGenerator.getInstance().generateDynamicReport(costsTable, str.toString());
                ReportGenerator.getInstance().showReport(print);
            } catch (Exception ex) {
                UIUtils.showErrorMessage("Произошли ошибки при печати таблицы");
            }
        }
    }//GEN-LAST:event_printButtonActionPerformed

    private void costsTableMouseClicked(java.awt.event.MouseEvent evt) {//GEN-FIRST:event_costsTableMouseClicked
        if (evt.getClickCount() == 2) {
            if (SecurityManager.getDefault().getCurrentPerson().getIsAdmin()) {
                Cost selection = getCostSelection();
                if (null != selection) {
                    CostDialog dialog = new CostDialog(WindowManager.getDefault().getMainWindow(), true);
                    dialog.setTitle("Редактировать расход");
                    dialog.setCostTableModel(costTableModel);
                    dialog.setCost(selection);
                    dialog.setLocationRelativeTo(null);
                    dialog.setVisible(true);
                }
            } else {
                UIUtils.notifyOperationNotAllowed();
            }
        }
    }//GEN-LAST:event_costsTableMouseClicked

    private void deleteItemActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_deleteItemActionPerformed
        if (!SecurityManager.getDefault().getCurrentPerson().getIsAdmin()) {
            UIUtils.notifyOperationNotAllowed();
            return;
        }
        Cost toDelete = getCostSelection();
        if (null != toDelete) {
            CostDataProvider.getInstance().deleteCostByPrimaryKey(toDelete.getId());
            costTableModel.dataRemoved(toDelete);
        }
    }//GEN-LAST:event_deleteItemActionPerformed

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton applyFilterButton;
    private javax.swing.JPopupMenu costPopuMenu;
    private javax.swing.JComboBox costTypeComboBox;
    private org.jdesktop.swingx.JXTable costsTable;
    private javax.swing.JMenuItem deleteItem;
    private org.jdesktop.swingx.JXDatePicker endDatePicker;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JButton printButton;
    private javax.swing.JButton refreshCostTypesButton;
    private javax.swing.JButton resetFilterButton;
    private org.jdesktop.swingx.JXDatePicker startDatePicker;
    private javax.swing.JLabel summaLabel;
    // End of variables declaration//GEN-END:variables
    @Override
    public void componentOpened() {
        // TODO add custom code on component opening
    }

    @Override
    public void componentClosed() {
        // TODO add custom code on component closing
    }

    void writeProperties(java.util.Properties p) {
        // better to version settings since initial version as advocated at
        // http://wiki.apidesign.org/wiki/PropertyFiles
        p.setProperty("version", "1.0");
        // TODO store your settings
    }

    void readProperties(java.util.Properties p) {
        String version = p.getProperty("version");
        // TODO read your settings according to their version
    }

    protected Cost getCostSelection() {
        if (costsTable.getSelectedRow() > -1) {
            Cost cost = (Cost) costsTable
                    .getValueAt(costsTable.getSelectedRow(), -1);
            return cost;
        }
        return null;
    }

    protected void customInit() {
        startDatePicker.setFormats(DateUtils.getSimpleDateFormat());
        endDatePicker.setFormats(DateUtils.getSimpleDateFormat());
        costTypeComboBox.setModel(new CostTypeComboBoxModel());
    }

    public double round(double value, int places) {
        long factor = (long) Math.pow(10, places);
        value = value * factor;
        long tmp = Math.round(value);
        return (double) tmp / factor;
    }
}
